package middleware

import (
	"errors"
	"github.com/gin-gonic/gin"
	"organoid_public/domain/sample"
	"organoid_public/domain/sample/service"
	"organoid_public/global"
	"organoid_public/pkg/response"
)

type LoginAuthMiddleware struct {
	svc      service.UserServiceInterface
	response *response.GinRestResponse
}

func NewLoginAuthMiddleware(response *response.GinRestResponse) *LoginAuthMiddleware {

	domainSvc, err := sample.Service()
	if err != nil {
		global.Log.Error("middleware", "login_auth", "function", "SetupRbac", "error", err.Error())
		panic(err)
	}

	return &LoginAuthMiddleware{
		svc:      domainSvc.UserSvc,
		response: response,
	}
}

func (l *LoginAuthMiddleware) HandleFunc(c *gin.Context) {
	var (
		Token    string
		response = l.response.New(c)
	)

	Token = c.Request.Header.Get("Token")
	if len(Token) <= 0 {
		response.Error(errors.New("非法请求")).ToJSON()
		return
	}

	jwtTokenObj, err := l.svc.CheckAuth(Token)
	if err != nil {
		response.Error(err).ToJSON()
		return
	}
	c.Set("userId", jwtTokenObj.Uid)
	c.Set("userName", jwtTokenObj.Name)
	c.Set("tokenId", jwtTokenObj.Id)
}
